﻿using System.Web.UI;
using System.Web.UI.WebControls;
using Google.Analytics.BusinessLogic;
using Google.Analytics.Common;
using Google.Analytics.Model;
using Microsoft.Practices.Unity;

namespace Google.Analytics.Web.DropDowns
{
    public class AccountsDropDown : DropDownList
    {
        #region Public Properties
        
        private const string authKey = "authKey";

        /// <summary>
        /// Authentication details using <see cref="AuthState"/> object
        /// </summary>
        [PersistenceMode(PersistenceMode.InnerProperty)]
        public AuthState Authentication
        {
            get { return (AuthState) ViewState[authKey]; }
            set { ViewState[authKey] = value; }
        }

        #endregion

        #region UnityContainer

        private UnityContainer analyticsContainer;
        /// <summary>
        /// Gets the unity container to resove the 
        /// </summary>
        public UnityContainer AnalyticsContainer
        {
            get
            {
                if (analyticsContainer == null)
                {
                    analyticsContainer = (UnityContainer)Page.Application["Google.Analytics"];
                    if (analyticsContainer == null) throw new AnalyticsException(ExceptionText.InvalidUnityContainer);
                }
                return analyticsContainer;
            }
        }
        #endregion

        /// <summary>
        /// DataBind override
        /// </summary>
        public override void DataBind()
        {
            //if no datasource is set and no items, load accounts
            if (DataSource == null && Items.Count == 0)
            {
                var manager = AnalyticsContainer.Resolve<DataManager>();
                var auth = Authentication;
                DataSource = manager.GetAccounts(ref auth);
                Authentication = auth;
            }
            base.DataBind();
        }
    }
}
